//
//  ZCPublishView.swift
//  weibo
//
//  Created by 张城 on 16/7/28.
//  Copyright © 2016年 张城. All rights reserved.
//

import UIKit
import pop

class ZCPublishView: UIView {
    var target: UIViewController?
    
    
    private lazy var bgImgView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    private lazy var logoImgView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    lazy var publishButtonInfos: [ZCPublishButtonInfo] = [ZCPublishButtonInfo]()
    
    lazy var buttons: [ZCPublishButton] = [ZCPublishButton]()
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        //        backgroundColor = UIColor.redColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        addSubview(bgImgView)
        addSubview(logoImgView)
        addChildButton()
        
        bgImgView.snp_makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        
        logoImgView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(150)
        }
        
    }
    
    // TODO
    func addChildButton() {
        self.publishButtonInfos = getPublishButtonInfos()
        
        let buttonW: CGFloat = 80
        let buttonH: CGFloat = 110
        let margin = (UIScreen.mainScreen().bounds.width - 3*buttonW)/4
        for (i , value) in publishButtonInfos.enumerate() {
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            
            let button = ZCPublishButton()
            button.publishButtonInfo = value
            
            button.setImage(UIImage(named: value.icon ?? ""), forState: .Normal)
            button.setTitle(value.title, forState: .Normal)
            button.frame = CGRectMake(margin+(margin+buttonW)*col, (margin+buttonW)*row + SCREENH, buttonW, buttonH)
            addSubview(button)
            button.addTarget(self, action: #selector(ZCPublishView.clickthisButton(_:)), forControlEvents: .TouchUpInside)
            buttons.append(button)
            
        }
    }
    
    func clickthisButton(button: ZCPublishButton) {
        
        UIView.animateWithDuration(0.3, animations: {
            
            for value in self.buttons  {
                
                value.alpha = 0.2
                
                if value == button {
                    
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) in
             
              UIView.animateWithDuration(0.3, animations: { 
                
                for value in self.buttons{
                value.alpha = 1
                value.transform = CGAffineTransformIdentity
                }
                }, completion: { (_) in
                    
                    guard let vcName = button.publishButtonInfo?.nextvc else{
                        return
                    }
                    
                    guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                        return
                    }
                    guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else{
                        return
                    }
                    
                    self.target?.presentViewController(UINavigationController(rootViewController: cn.init()), animated: false, completion: { 
                        self.removeFromSuperview()
                    })
                    
                    
              })
        }
    }
    
    func getPublishButtonInfos() -> [ZCPublishButtonInfo] {
        
        let file = NSBundle.mainBundle().pathForResource("compose", ofType: "plist")
        
        let fileArray = NSArray(contentsOfFile: file!)
        
        var temp: [ZCPublishButtonInfo] = [ZCPublishButtonInfo]()
        
        for dic in fileArray! {
            let model = ZCPublishButtonInfo(dic: dic as! [String : AnyObject])
            
            temp.append(model)
        }
        
        return temp
    }
    
    
    func publishViewShow(target: UIViewController) {
        
        self.target = target
        
        target.view.addSubview(self)
        
        setupButtonAnim(true)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setupButtonAnim(false)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            
            self.removeFromSuperview()
        }
        
        
    }
    
    func setupButtonAnim(isUp: Bool) {
        let margin: CGFloat = isUp ? -350 : 350
        
        let array = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        for (i , value) in array {
            
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            anim.toValue = NSValue(CGPoint: CGPointMake(value.center.x, value.center.y + margin))
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.03
            anim.springBounciness = 10
            anim.springSpeed = 8
            
            value.pop_addAnimation(anim, forKey: nil)
        }
    }
    
}
